package com.intexh.quickandroid.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.StrictMode;
import android.text.TextUtils;

import com.intexh.quickandroid.BuildConfig;
import com.intexh.quickandroid.helper.UserHelper;
import com.intexh.quickandroid.module.chat.ChatHelper;
import com.intexh.quickandroid.module.chat.bean.UserInfo;
import com.intexh.quickandroid.net.NetworkManager;
import com.mob.MobSDK;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created by FrankZhang on 2017/11/14.
 */

public class MainApplication extends Application {

    private final static ArrayList<BaseActivity> activitys = new ArrayList<>();
    private final static ArrayList<Activity> tempActivitys = new ArrayList<>(); //临时记录activity界面
    public final static Map<String,Activity> webActivityList = new HashMap<>();
    private static MainApplication instance;

    // 创建一个单线程的线程池。
    // 用于写入数据库
    public static ExecutorService persistenceExecutorService = Executors
            .newSingleThreadExecutor();
    private ExecutorService multiThreadExecutorService;


    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
//        MultiDex.install(this);
        if(!BuildConfig.IS_DEBUG){  //非debug模式 初始化异常捕捉
            CrashReport.initCrashReport(getApplicationContext(), BuildConfig.BUGLY_APP_ID, BuildConfig.IS_DEBUG);
        }
        NetworkManager.INSTANCE.init(this); //初始化网络请求
		MobSDK.init(this);
//		if(UserHelper.isLogin()){
//            JpushController.setAlias(MainApplication.getAppContext(),UserHelper.getUser().getPush_id());
//        }
        initChatIM();
    }

    //64k 分包
//    @Override
//    protected void attachBaseContext(Context base) {
//        super.attachBaseContext(base);
//        MultiDex.install(this);
//    }

    private void initChatIM() {
        UserInfo userInfo = new UserInfo();
        if(!TextUtils.isEmpty(UserHelper.getCurrentToken())) {
            userInfo.setUid(UserHelper.getUser().getUserid());
            userInfo.setAvatar(UserHelper.getUser().getMember_avatar());
            userInfo.setDisplay_name(UserHelper.getUser().getUsername());
            userInfo.setChat_id(UserHelper.getUser().getChat_id());
            userInfo.setChat_pwd(UserHelper.getUser().getChat_pwd());
        }
        ChatHelper.getInstance().init(getApplicationContext(),userInfo);
        ChatHelper.getInstance().login(userInfo.getChat_id(),userInfo.getChat_pwd());
    }


    public static Context getAppContext() {
        return instance.getApplicationContext();
    }

    //全局记录
    public static void addActivity(BaseActivity context) {
        activitys.add(context);
    }
    public static void removeActivity(BaseActivity context) {
        activitys.remove(context);
    }
    public static void finishAllActivity() {
        Activity activity;
        for (int i = activitys.size() - 1; i >= 0; i--) {
            activity = activitys.get(i);
            if (activity != null && !activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    //临时
    public static void addTempActivity(Activity context) {
        tempActivitys.add(context);
    }
    public static void removeTempActivity(Activity context) {
        tempActivitys.remove(context);
    }
    public static void finishAllTempActivity() {
        Activity activity;
        for (int i = tempActivitys.size() - 1; i >= 0; i--) {
            activity = tempActivitys.get(i);
            if (activity != null && !activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    //网页
    public static void addActivity(String key,Activity context) { //记录打开的activity
        webActivityList.put(key,context);
    }
    public static void removeActivity(String key) {
        webActivityList.remove(key);
    }
    public static void finishAllWebActivity() {
        Activity activity;
        for(Map.Entry<String,Activity> entry:webActivityList.entrySet()){
            activity = entry.getValue();
            if (activity != null && !activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    //显示登录凭证失效在当前显示的界面上
    public static void showTokenInvalidHint(){
        BaseActivity activity = activitys.get(activitys.size()==0?0:activitys.size() - 1);
        activity.showTokenInvalidHintDialog();
    }

    public static MainApplication getInstance() {
        return instance;
    }

    //线程池用于保存数据库
    public ExecutorService getExecutor(int size) {
        if (size <= 1) {
            return persistenceExecutorService;
        } else {
            if (multiThreadExecutorService == null) {
                multiThreadExecutorService = Executors.newFixedThreadPool(5);
            }
            return Executors.newFixedThreadPool(5);
        }
    }

    /**
     * 载入调试设置
     */
    private void initDebugSetting() {
        if (BuildConfig.IS_DEBUG) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectCustomSlowCalls() //API等级11，检查代码执行缓慢
//                    .detectDiskReads()        //磁盘读写检查
//                    .detectDiskWrites()
//                    .detectNetwork()   // or .detectAll() for all detectable problems
                    .penaltyDialog() //弹出违规提示对话框
                    .penaltyLog() //在Logcat 中打印违规异常信息
//                    .penaltyFlashScreen() //API等级11 会造成屏幕闪烁，不过一般的设备可能没有这个功能。
                    .build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
//                    .detectLeakedSqlLiteObjects()   //用来检查 SQLiteCursor 或者 其他 SQLite对象是否被正确关闭
                    .detectLeakedClosableObjects() //API等级11    用于资源没有正确关闭时提醒
                    .detectActivityLeaks()      //activity 内存泄漏检测
                    .penaltyLog()
//                    .penaltyDeath()     //当触发违规条件时，直接Crash掉当前应用程序。
                    .build());
        }
    }
}
